package com.android.openapp.ui;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.util.Log;

import com.android.openapp.data.Place;
import com.android.openapp.services.Controller;
import com.socrata.api.RequestException;
import com.socrata.data.View;

/**
 * 
 * @author Allieri Tommaso
 * Thread di download dei metadati
 *
 */
public class Metainit extends Thread{
	
	public static int flag=0; //flag di download
	public static int worked=0; //flag worked***********
	
	Context mContext;
	
	Integer index;
	public Metainit(Integer index, Context context) {
		this.index=index;
		mContext = context;
	}
	
	@Override
	public void run() {
		
		
			Log.i("test ","thread download");
			download();
			
				
			
		
		super.run();
	}
	synchronized void download(){
		View v=new View();
		View temp=new View();
		try {
			synchronized (Place.listmetadati) {
				//nel caso ci sia gia' il file dei metadati
				FileInputStream fin = mContext.openFileInput(Place.datasetM[index].toLowerCase());
				temp = v.getLocal(fin, View.class);
				Log.d("Download function",this.getName()+ " "+ Integer.toString(index));
				//Log.d("api_id",temp.getColumnById(9897690).getName());
				Log.d("Download function",this.getName()+ "pippo "+ temp.getDescription());
				Place.listmetadati.set(index, temp);
				flag++;
				worked++;
				Log.v("download", "i metadati "+index+" sono presenti in memoria e sono stati caricati");
			}

		} catch (RequestException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			worked++;
			Log.e("download method","error to download");
		} catch (FileNotFoundException e) {
			FileOutputStream fout;
			try {
				fout = mContext.openFileOutput(Place.datasetM[index].toLowerCase(), Context.MODE_PRIVATE);
				temp = v.get(fout, Place.datasetM[index].toLowerCase(), Controller.c, View.class);
				fout.close();
				Place.listmetadati.set(index, temp);
				flag++;
				worked++;
				Log.v("download", "i metadati "+index+" NON erano presenti in memoria e sono stati scaricati");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (RequestException e2) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			Log.i(this.getName(),"metadati "+Integer.toString(index)+" scaricato");
		}

	}
}